package com.app.service.impl;

import com.app.dao.ShareDao;
import com.app.dao.UserDao;
import com.app.pojo.*;
import com.app.service.IFileService;
import com.app.service.IUserService;
import com.app.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;

import static cn.hutool.core.lang.Console.log;

@Service
public class UserService implements IUserService {


    private final UserDao userDao;
    private final ShareDao shareDao;

    public UserService(UserDao userDao, ShareDao shareDao) {
        this.userDao = userDao;
        this.shareDao = shareDao;
    }

    @Override
    public UserInfo getUserInfoById(String userId) {
        try {
            UserInfo userInfo = userDao.finUserInfoById(userId);
            userInfo.signature="一袋键仙蛋炒饭";
            userInfo.storageUse=1024;
            userInfo.labelNum = 10;
            userInfo.beCollected=20;
            return userInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public String loginByName(String username, String password) {
        try {
            log("用户名登录：",username,password);
            String userId = userDao.finUserIdByName(username);
            if (ObjectUtils.isEmpty(userId)) return userId;
            log(userId);

            String pw = userDao.finPasswdById(userId);
            log(pw);
            if (password.equals(pw)) return userId;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String loginByEmail(String email,String password) {
        try {
            log("邮箱登录：",email,password);
            String userId = userDao.finUserIdByEmail(email);
            log(userId);
            if (ObjectUtils.isEmpty(userId)) return userId;

            String pw = userDao.finPasswdById(userId);
            log(pw);
            if (password.equals(pw)) return userId;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean isUserExistByAccount(String account){
        return !ObjectUtils.isEmpty(account.contains("@")?
                userDao.finUserIdByName(account)
                :userDao.finUserIdByEmail(account));
    }
    @Override
    public boolean isUserExist(String username, String email){
        return !ObjectUtils.isEmpty(userDao.finUserIdByName(username))
                ||!ObjectUtils.isEmpty(userDao.finUserIdByEmail(email));
    }
    /**
     *
     * @param username 用户昵称
     * @param password 密码
     * @param email 邮箱
     * @return SUCCESS，USER_ALREADY_EXIST，SYSTEM_ERROR，
     */
    @Override
    public boolean register(String username,String email,String password) {
        //新建id
        String userId=""+new Date().getTime()+(int)(Math.random()*10000);
        try {//会更改数据库，开启事务
            doRegisterTrans(userId,username,email,password);
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=12000,rollbackFor=Exception.class)
    public void doRegisterTrans(String userId,String username,String email,String password){
        String error="";
        if(userDao.addUserInfo(userId,username,email)==1){
            if (userDao.addUserPw(userId,password)==1){
                //添加到数据库
                if (FileUtils.makeUserFiles(userId))
                    return;
                else error="创建用户文件失败";
            } else error="用户密码添加失败";
        }else error="用户信息添加失败";
        throw new RuntimeException(error);
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=12000,rollbackFor=Exception.class)
    public boolean closeAccount(String userId) {
        //删除用户相关表
        if (userDao.deleteUser(userId)<1|| shareDao.delSharesById(userId)<1|| userDao.deleteLabelsById(userId)<1) {
            makeException("删除失败！");
            return false;
        } else{
            //删除文件
            FileUtils.removeUserFiles(userId);
            return true;
        }
    }
    private void makeException(String msg){
        throw new RuntimeException(msg);
    }
}
